﻿using System.Data;
using System.IO;
using UnityEngine;
using UnityEditor;
using ExcelDataReader;

public static class DataTableGeneratorMenu
{
    private static string JSON_TABLE_PATH = $"{UnityEngine.Application.dataPath}/GameRes/Tables";
    
    [MenuItem("Tools/DataTableTools/DataTableExcelToJson", false, 50)]
    private static void DataTableExcelAndToTxt()
    {
        string excelPath = $"{Application.dataPath}/../../Excels";
        excelPath = excelPath.Replace("/", "\\");
        string[] residentDataTableNames = Directory.GetFiles(excelPath, "*.xlsx");
        foreach (string dataTableName in residentDataTableNames)
        {
            Debug.Log($"发现Excel文件:\"<color=#00FF00>{dataTableName}</color>\"");
            ExcelToJson(dataTableName);
        }

        AssetDatabase.Refresh();
    }

    private static void ExcelToJson(string excelPath)
    {
        string jsonStr = XlsxToJsonStr(excelPath);
        Debug.Log($"Excel转换Json成功, json内容为: <color=#FFFF00>{jsonStr}</color>");
        
        string jsonPath = $"{JSON_TABLE_PATH}/{Path.GetFileNameWithoutExtension(excelPath)}.json.txt";
        if (!File.Exists(jsonPath))
        {
            File.Create(jsonPath).Close();
        }
        
        using (StreamWriter streamWriter = new StreamWriter(jsonPath))
        {
            streamWriter.WriteLine(jsonStr);
            streamWriter.Close();
        }
    }
    
    private static string XlsxToJsonStr(string excelPath)
    {
        string jsonStr = "";
        
        using FileStream fileStream = File.Open(excelPath, FileMode.Open);
        var excelDataReader = ExcelReaderFactory.CreateReader(fileStream);
        DataSet result = excelDataReader.AsDataSet();
        
        int columns = result.Tables[0].Columns.Count;
        int rows = result.Tables[0].Rows.Count;
        
        jsonStr = "[";
        for (int i = 4; i < rows; i++)
        {
            jsonStr += "{";
            for (int j = 1; j < columns; j++)
            {
                string typeName = result.Tables[0].Rows[2][j].ToString();
                if (!string.IsNullOrEmpty(typeName))
                {
                    string dataName = result.Tables[0].Rows[1][j].ToString();
                    string data = MoreTypedWriting(typeName, result.Tables[0].Rows[i][j].ToString());
                    jsonStr += $"\"{dataName}\":{data},";
                }
            }
            jsonStr = jsonStr.Remove(jsonStr.Length - 1, 1);
            jsonStr += "},";
        }
        jsonStr = jsonStr.Remove(jsonStr.Length - 1, 1);
        jsonStr += "]";
        fileStream.Close();

        return jsonStr;
    }

    private static string MoreTypedWriting(string typeName, string data)
    {
        if (typeName == "string")
        {
            return $"\"{data}\"";
        }
        else if (typeName == "int")
        {
            return data;
        }
        else if (typeName == "float")
        {
            return data;
        }
        else if (typeName == "bool")
        {
            return data;
        }
        
        throw new System.Exception($"不支持的类型: {typeName}");;
    }
}
